# -*- coding: utf-8 -*-

'''
政务物联网APP服务
'''

from gov.data_process.data import DataProcess
from pao.data import process_db
import pandas as pd
import json
import uuid
import datetime
from flask import session


class GovNetThingAppService(DataProcess):

    def return_all_collection_data(self, collectionname):
        # 返回单表的全部数据，需要输入collection的名字
        list_tep = ''

        def process_func(db):
            nonlocal list_tep
            collection1 = db[collectionname]
            cur = collection1.find({})
            list_tep = list(cur[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        pd_tep = pd.DataFrame(list_tep)
        pd_tep = pd_tep.drop(["_id"], axis=1)
        res = pd_tep.to_json(orient='index', force_ascii=False)
        return res

    def return_netthing_object(self, userid):
        # 输入userid，返回该用户绑定的所有物联网对象的信息
        list_tep = ''

        def process_func(db):
            nonlocal list_tep
            collection1 = db['PT_NETTHING_PERSON_INFO']
            cur = collection1.find({'USER_ID': userid})
            list_tep = list(cur[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        pd_tep = pd.DataFrame(list_tep)
        object_id = pd_tep['NETTHING_OBJECT_ID'].tolist()
        object_list = ''

        def process_func1(db):
            nonlocal object_list
            collection1 = db['PT_NETTHING_OBJECT']
            res_cur = collection1.find({'ID': {'$in': object_id}})
            object_list = list(res_cur[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func1)
        object_df = pd.DataFrame(object_list)
        object_df = object_df.drop(["_id"], axis=1)
        res = object_df.to_json(orient='index', force_ascii=False)
        return res

    def login_confirm(self,user_name,password,platform_type,platform_version,ip,app_type):
        #登录确认,若登录成功，则修改登录时间为当前时间，并在登录记录表中添加一条记录
        #返回结果为False代表密码错误
        #返回结果为1代表登录成功且非首次登录
        #返回结果为2代表登录成功且为首次登录
        query_res=''
        def process_func(db):
            nonlocal query_res
            collection1 = db['PT_LOGIN_AUTHENTICATE']
            cur = collection1.find({'AUTH_ID': user_name})
            query_res = list(cur[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        query_df=pd.DataFrame(query_res)
        if query_df.empty :
            return False
        password_T=query_df['AUTH_TOKEN'].iloc[0]
        login_time=query_df['LOGIN_TIMIE'].iloc[0]
        login_id=query_df['ID'].iloc[0]
        userid=query_df['USER_ID'].iloc[0]
        if password_T==password :
            #登录记录表中增加记录
            dq_time=datetime.datetime.now()
            data={
                'ID':uuid.uuid1(),
                'LOGIN_ID':login_id,
                'PLATFORM_TYPE':platform_type,
                'PLATFORM_VERSION':platform_version,
                'LOGIN_TIME':dq_time,
                'IP':ip,
                'APP_TYPE':app_type}
            def process_func(db):
                collection1 = db['PT_LOGIN_RECORD']
                collection1.insert(data)
            process_db(self.db_addr, self.db_port, 'GovNetThing', process_func1)
            #修改登录验证表中的logintime
            myquery={'AUTH_ID': user_name}
            newvalues={'$set':{'LOGIN_TIMIE':dq_time}}
            def process_func2(db):
                collection1 = db['PT_LOGIN_AUTHENTICATE']
                collection1.update_one(myquery,newvalues)
            process_db(self.db_addr, self.db_port, 'GovNetThing', process_func2)
            if login_time == '' :
                return {'res':2,'user_id':userid}  #首次登录返回2
            else :
                return {'res':1,'user_id':userid} #非首次登录返回1
        elif password_T!=password :
            return False
        
    def query_list(self,condition,collection_name,page,number,sort_key):
        #列表查询结果
        #根据输入的表名，查询条件，查询的排序关键字，页码，条目，返回结果
        skip_num=(page-1)*number
        res_list=''
        def process_func(db):
            nonlocal res_list
            collection=db[collection_name]
            cur=collection.find(condition).sort(sort_key).skip(skip_num).limit(number)
            res_list=list(cur[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        res_df=pd.DataFrame(res_list)
        res = res_df.to_json(orient='index', force_ascii=False)
        return res
    
    def query_basic_data(self,condition,collection_name):
        #查询基础数据，仅支持单表查询，根据查询条件和表名返回查询结果
        res_list=''
        def process_func(db):
            nonlocal res_list
            collection=db[collection_name]
            cur=collection.find(condition)
            res_list=list(cur[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        res_df=pd.DataFrame(res_list)
        res = res_df.to_json(orient='index', force_ascii=False)
        return res

    def insert_sigle_data(self,collection_name,insertdata):
        #插入单条数据
        def process_func(db):
            collection=db[collection_name]
            collection.insert(insertdata)
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        
    def stat_event_number(self,collection_name,condition):
        #统计时间数量
        #根据查询表名和查询条件，返回查询的总条目数
        res_list=''
        def process_func(db):
            nonlocal res_list
            collection=db[collection_name]
            cur=collection.find(condition)
            res_list=list(cur[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        res_df=pd.DataFrame(res_list)
        res=len(res_df)
        return res
    
    def export_template(self,collection_name):
        #导出模板，导出指定表的结构
        res_list=''
        def process_func(db):
            nonlocal res_list
            collection=db[collection_name]
            cur=collection.find({}).limit(1)
            res_list=list(cur[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        res_df=pd.DataFrame(res_list)
        del res_df['_id']
        del res_df['ID']
        for i in range(len(res_df.iloc[0,:])):
            res_df.iloc[0,i]=''
        res=res_df.to_json(orient='index', force_ascii=False)
        return res
            
    def import_data(self,collection_name,insert_data):
        #导入数据到指定collection，并添加一列ID
        length=len(insert_data)
        ID=[uuid.uuid1() for x in range(length)]
        insert_data['ID']=ID
        def process_func(db):
            collection=db[collection_name]
            collection.insert(insert_data)
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        
    def query_Data_monitor_map(self):
        #查询数据监控地图数据
        collection_name1='PT_NETTHING_ACCIDENT_MONITOR'
        condition1={'EMERGENT_LEVEL':{'$in':['重大事故','重大危险','一般事故','一般危险']}}
        event_df=self.query_basic_data(self,condition1,collection_name1)
        Rtuid=event_df['RTU_ID'].tolist()
        collection_name2='PT_NETTHING_OBJECT'
        condition2={'RTU_ID':{'$in':Rtuid}}
        loc_df=self.query_basic_data(self,condition2,collection_name2)
        res_df=pd.merge(event_df,loc_df,how='left',on='RTU_ID')
        pro_type=self.return_all_collection_data(self, 'PT_NETTHING_PRODUCT_TYPE')
        res_df=pd.merge(res_df,pro_type,how='left',left_on='PRODUCT_TYPE_ID',right_on='ID')
        device_type=self.return_all_collection_data(self, 'PT_NETTHING_DEVICE_TYPE')
        res_df=pd.merge(res_df,device_type,how='left',left_on='DEVICE_TYPE_ID',right_on='ID')
        res_df=res_df[['RTU_ID','LONGITUDE','LATITUDE','EMERGENT_LEVEL','STATE'
                       ,'PRODUCT_TYPE_ID','ADDRESS','NAME','DEVICE_TYPE_ID','PRODUCT_TYPE_ID']] #可根据需要修改
        res=res_df.to_json(orient='index', force_ascii=False)
        return res

            
        


        
        
        